$(document).ready(function() {
    var VAL ={
        NORMAL     : "0000000"  ,
        EVT_USER   : $("#userId").text(),
        T_XPINQSHT : "XPINQSHT" ,
        T_XPBISOPE : "XPBISOPE" ,
        T_XPPRDSCRP : "XPPRDSCRP"
    };
    var domObj = {
			$window : $(window),
			$pnlInfoGrdDiv : $("#pnlInfoGrdDiv"),
			$pnlInfoGrd : $("#pnlInfoGrd")
	};
    /**
     * All controls's jquery object/text
     * @type {Object}
     */
    var controlsQuery = {
        W              : $(window)         ,
        pnlIDInput   : $("#pnlIDInput")    ,
//        scrpUserInput : $("#scrpUserInput"),
        boxIDInput : $("#boxIDInput"),
        remarkInput : $("#remarkInput"),
        mainGrd   :{
            grdId     : $("#pnlInfoGrd")   ,
            grdPgText : "#pnlInfoPg"       ,
            fatherDiv : $("#pnlInfoGrdDiv")
        }
    };

    /**
     * All button's jquery object
     * @type {Object}
     */
    var btnQuery = {
        del : $('#delete_btn'),
        clr : $('#clear_btn'),
        add : $('#add_btn'),
        scrp : $('#scrp_btn'),
        scrp_cancel : $('#scrp_cancel_btn'),
        query_all_btn : $('#query_all_btn')
    };

    /**
     * All tool functions
     * @type {Object}
     */
    var toolFunc = {
        resetJqgrid :function(){
            controlsQuery.W.unbind("onresize");
            controlsQuery.mainGrd.grdId.setGridWidth(controlsQuery.mainGrd.fatherDiv.width()*0.80);
            controlsQuery.W.bind("onresize", this);
        },
        clearInput : function(){
            controlsQuery.pnlIDInput.val("");
            controlsQuery.boxIDInput.val("");
            controlsQuery.remarkInput.val("");
        }
    };

    /**
     * All button click function
     * @type {Object}
     */
    var btnFunc = {
        //Clear
        clear_func : function(){
            controlsQuery.mainGrd.grdId.jqGrid("clearGridData");
        },
        //Delete
        del_func : function(){
            var i, j,
                curGrid = controlsQuery.mainGrd.grdId,
                ids = curGrid.jqGrid("getGridParam","selarrrow");
            for ( i = 0, j = ids.length; i < j; i++) {
                curGrid.jqGrid('delRowData', ids[0]);
            }
        },
        //ADD
        add_func : function(){
            var i,j,
                prd_id,
                inObj,
                inObj2,
                outObj,
                outObj2,
                rowIds,
                curRowData,
                curGrid = controlsQuery.mainGrd.grdId;

            prd_id = $.trim(controlsQuery.pnlIDInput.val());
            if(!prd_id){
                showErrorDialog("","请输入ID");
                return false;
            }

            rowIds = curGrid.jqGrid('getDataIDs');
            if(rowIds){
                for(i = 0, j = rowIds.length; i < j; i++) {
                    curRowData = curGrid.jqGrid('getRowData', rowIds[i]);
                    if(curRowData['prd_seq_id'] == prd_id){
                        showErrorDialog("", prd_id + "已经存在！");
                        return false;
                    }
                }
            }

            inObj = {
                trx_id      : VAL.T_XPINQSHT,
                action_flg  : 'T'           ,
                prd_seq_id  : prd_id
            };
            outObj = comTrxSubSendPostJson(inObj);
            if(outObj.rtn_code == VAL.NORMAL){
                if (outObj.hasOwnProperty("prd_tbl")) {
                    //Query scrp ope
                    if("SCRP" === outObj.prd_tbl.prd_stat){
                        inObj2 = {
                            trx_id      : VAL.T_XPBISOPE,
                            action_flg  : 'Q'           ,
                            iary : {
                                ope_id : outObj.prd_tbl.cr_ope_id_fk,
                                ope_ver : outObj.prd_tbl.cr_ope_ver_fk
                            }
                        };
                        outObj2 = comTrxSubSendPostJson(inObj2);
                        if(outObj2.rtn_code == VAL.NORMAL){
                            outObj.prd_tbl.scrp_ope = outObj2.oary.ope_dsc;
                        }
                    }
                    curGrid.jqGrid('addRowData', $.jgrid.randId(), outObj.prd_tbl);
                    toolFunc.clearInput();
                }else{
                    showErrorDialog("", "ID ["+ prd_id +"] 不存在，请确认！");
                    return false;
                }
            }
        },
        scrp_func : function(){
            var inObj,
                outObj,
//                scrp_usr,
                iary = [],
                ids,
                prd_cnt,
                rowData,
                curGrid = controlsQuery.mainGrd.grdId,
                i;

//            scrp_usr = $.trim(controlsQuery.scrpUserInput.val());
//            if(!scrp_usr){
//                showErrorDialog("","请输入操作人员工号!");
//                return false;
//            }

            ids = curGrid.jqGrid("getGridParam","selarrrow");
            prd_cnt = ids.length;
            if( prd_cnt === 0 ){
                showErrorDialog("","请勾选需要报废的ID!");
                return false;
            }

            for( i = 0; i < prd_cnt; i++ ){
                rowData = curGrid.jqGrid('getRowData', ids[i]);
                iary.push({
                    prd_seq_id : rowData['prd_seq_id']
                });
            }

            inObj = {
                trx_id      : VAL.T_XPPRDSCRP,
                action_flg  : 'S'            ,
                evt_usr     : VAL.EVT_USER   ,//操作用户改为登陆用户
                prd_cnt     : prd_cnt        ,
                scrp_note   : $.trim(controlsQuery.remarkInput.val()),
                iary        : iary
            };
            outObj = comTrxSubSendPostJson(inObj);
            if(outObj.rtn_code == VAL.NORMAL){
                showSuccessDialog("报废成功！");
            }
        },
        scrp_cancel_func : function(){
            var inObj,
                outObj,
//                scrp_cancel_usr,
                scrp_cancel_box,
                iary = [],
                ids,
                prd_cnt,
                rowData,
                curGrid = controlsQuery.mainGrd.grdId,
                i;

//            scrp_cancel_usr = $.trim(controlsQuery.scrpUserInput.val());
//            if(!scrp_cancel_usr){
//                showErrorDialog("","请输入操作人员工号!");
//                return false;
//            }
            scrp_cancel_box = $.trim(controlsQuery.boxIDInput.val());
            if(!scrp_cancel_box){
                showErrorDialog("","请输入要转入的箱号!");
                return false;
            }

            ids = curGrid.jqGrid("getGridParam","selarrrow");
            prd_cnt = ids.length;
            if( prd_cnt === 0 ){
                showErrorDialog("","请勾选需要取消报废的ID!");
                return false;
            }

            for( i = 0; i < prd_cnt; i++ ){
                rowData = curGrid.jqGrid('getRowData', ids[i]);
                iary.push({
                    prd_seq_id : rowData['prd_seq_id']
                });
            }

            inObj = {
                trx_id      : VAL.T_XPPRDSCRP,
                action_flg  : 'R'            ,
//                evt_usr     : scrp_cancel_usr,
                evt_usr     : VAL.EVT_USER   ,
                scrp_cancel_box : scrp_cancel_box,
                scrp_note   : $.trim(controlsQuery.remarkInput.val()),
                prd_cnt     : prd_cnt        ,
                iary        : iary
            };
            outObj = comTrxSubSendPostJson(inObj);
            if(outObj.rtn_code == VAL.NORMAL){
                showSuccessDialog("取消报废成功！");
            }
        },
        query_all_btn_func : function(){
            var inObj,
                outObj;

            inObj = {
                trx_id      : VAL.T_XPPRDSCRP,
                action_flg  : 'Q'
            };
            outObj = comTrxSubSendPostJson(inObj);
            if(outObj.rtn_code == VAL.NORMAL){
                setGridInfo(outObj.oary, "#pnlInfoGrd");
            }
        }
    };
    /**
     * Bind button click action
     */
    var iniButtonAction = function(){
        btnQuery.del.click(function(){
            btnFunc.del_func();
        });
        btnQuery.clr.click(function(){
            btnFunc.clear_func();
        });
        btnQuery.add.click(function(){
            btnFunc.add_func();
        });
        btnQuery.scrp.click(function(){
            btnFunc.scrp_func();
        });
        btnQuery.scrp_cancel.click(function(){
            btnFunc.scrp_cancel_func();
        });
        btnQuery.query_all_btn.click(function(){
            btnFunc.query_all_btn_func();
        });
    };

    /**
     * grid  initialization
     */
    var iniGridInfo = function(){
        var infoCM = [
            {name: 'prd_seq_id',   index: 'prd_seq_id',   label: PRD_SEQ_ID_TAG   , width: PRD_SEQ_ID_CLM},
            {name: 'lot_id',       index: 'lot_id',       label: LOT_ID_TAG       , width: LOT_ID_CLM},
            {name: 'mdl_id_fk',    index: 'mdl_id_fk',    label: MDL_ID_TAG       , width: MDL_ID_CLM},
            {name: 'wo_id_fk',     index: 'wo_id_fk',     label: WO_ID_TAG        , width: WO_ID_CLM},
            {name: 'so_id_fk',     index: 'so_id_fk',     label: SO_NO_TAG        , width: WO_ID_CLM},
            {name: 'prd_stat'   ,  index: 'prd_stat',     label: STATUS_TAG       , width: PRD_STAT_CLM},
            {name: 'scrp_ope'   ,  index: 'scrp_ope',     label: SCRP_OPE_TAG     , width: OPE_ID_CLM},
            {name: 'evt_usr'   ,   index: 'evt_usr',      label: EVT_USR          , width: EVT_USR_CLM},
            {name: 'evt_timestamp',index: 'evt_timestamp',label: EVT_TIMESTAMP    , width: EVT_TIMESTAMP_CLM}
        ];
        controlsQuery.mainGrd.grdId.jqGrid({
            url:"",
            datatype:"local",
            mtype:"POST",
            height: 360,
            width: domObj.$pnlInfoGrdDiv.width(),
            shrinkToFit:false,
            scroll:true,
            rownumWidth : true,
            resizable : true,
            rowNum: 200,
            loadonce:true,
            multiselect : true,
            viewrecords:true,
            pager : controlsQuery.mainGrd.grdPgText,
            fixed: true,
            colModel: infoCM
        });
    };

    /**
     * Other action bind
     */
    var otherActionBind = function(){
        // Reset size of jqgrid when window resize
        controlsQuery.W.resize(function(){
            toolFunc.resetJqgrid();
        });

        controlsQuery.pnlIDInput.keydown(function(event){
            if(event.keyCode === 13){
                btnFunc.add_func();
            }
        });
    };

    /**
     * Ini view and data
     */
    var initializationFunc = function(){
        iniGridInfo();
        iniButtonAction();
        otherActionBind();
        toolFunc.clearInput();
    };

    initializationFunc();
    function resizeFnc(){        
    	comResize(controlsQuery.W,controlsQuery.mainGrd.fatherDiv,controlsQuery.mainGrd.grdId);

//    	var offsetBottom, divWidth;                                                              
//        
//		divWidth = domObj.$pnlInfoGrdDiv.width();                                   
//		offsetBottom = domObj.$window.height() - domObj.$pnlInfoGrdDiv.offset().top;
//		domObj.$pnlInfoGrdDiv.height(offsetBottom * 0.95);                          
//		domObj.$pnlInfoGrd.setGridWidth(divWidth * 0.99);                   
//		domObj.$pnlInfoGrd.setGridHeight(offsetBottom * 0.99 - 51);       
    };                                                                                         
    resizeFnc();                                                                               
    domObj.$window.resize(function() {                                                         
    	resizeFnc();                                                                             
	});      
});